package com.qn.servlet;

import com.alibaba.fastjson2.JSON;
import com.qn.entity.Product;
import com.qn.entity.ResultBean;
import com.qn.service.ProductServiceImpl;
import com.qn.service.ProductServiceInter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {
    //创建业务层对象
    private ProductServiceInter<Product> productServiceInter = new ProductServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建回写数据的对象
        ResultBean resultBean = new ResultBean(true);
        try {
            //获取参数id
            String id = request.getParameter("id");
            //调用业务逻辑层的方法
            int row = productServiceInter.deleteById(id);
            if (row > 0){
                //删除成功
                resultBean.setData("success");
            }else {
                //删除失败
                resultBean.setData("flag");
            }
        }catch (Exception e){
            //抛出异常信息
            e.printStackTrace();
            resultBean.setFlag(false);
            resultBean.setErrorMsg("删除服务器出现异常");
        }
        //回写数据
        response.getWriter().write(JSON.toJSONString(resultBean));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
